package com.dmgis.qxfw.dataservice.businessservice.cdtt.service.impl;


import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.msgmediumsmallscale;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.smallscale_station;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.contour_setting;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.dz_warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.potential_points;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.sl_warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.tour_stations;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.waterlogging_fcst;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ActualElemQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.SmallScaleSearch;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.cdtt.service.TowerSatelliteService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("TowerService")
public class TowersatelliteImpl  implements TowerSatelliteService {

    ProcessRequestController pc = new ProcessRequestController();

    @Resource
    private ITransformService iTransformService;
    @Override
    public Date getScaleNewDate() {
        // TODO 获取最新实况数据
        Date date = new Date();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(observtime,'yyyy-MM-dd HH24:MI:SS') as observtime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam(String.format("city like '%s%%'", DbConfig.CITY));
        selectRequest.setSort(new String[]{"observtime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            date = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            }).get(0).getObservtime();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return date;
    }


    @Override
    public List<SmallScaleStation> getCitySta() {
        // TODO 城市站点
        List<SmallScaleStation> resultList = new ArrayList<SmallScaleStation>();
        List<smallscale_station> dataList = new ArrayList<smallscale_station>();
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            // 获取查询字段
            List<String> columns = new ArrayList<String>();
            columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
            columns.add("stationname");
            columns.add("longitude");
            columns.add("latitude");
            columns.add("city");
            columns.add("county");

            selectRequest.setParam(
                    String.format("stationid like '5%%'  and  city like '%s%%'", DbConfig.CITY));
            selectParam.put("method", "smallscale_station");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<smallscale_station>>() {
            });
            // 赋值
            if (dataList.size() > 0) {
                for (smallscale_station station : dataList) {
                    SmallScaleStation scaleStation = new SmallScaleStation();
                    scaleStation.setCity(station.getCity());
                    scaleStation.setAltitude(station.getAltitude());
                    scaleStation.setCounty(station.getCounty());
                    scaleStation.setLatitude(station.getLatitude());
                    scaleStation.setStationID(station.getStationid());
                    scaleStation.setStationName(station.getStationname());
                    resultList.add(scaleStation);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return resultList;
    }


    @Override
    public List<tower_station> getTownStaList() {
        // TODO 自动站
        List<tower_station> resultList = new ArrayList<tower_station>();
        List<tower_station> dataList = new ArrayList<tower_station>();
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            // 获取查询字段
            List<String> columns = new ArrayList<String>();
            columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
            columns.add("stationname");
            columns.add("longitude");
            columns.add("latitude");
            columns.add("stationname");
            columns.add("county");
            selectParam.put("method", "tower_station");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<tower_station>>() {
            });
            // 赋值
            if (dataList.size() > 0) {
                for (tower_station station : dataList) {
                    tower_station scaleStation = new tower_station();
                    scaleStation.setCounty(station.getCounty());
                    scaleStation.setLatitude(station.getLatitude());
                    scaleStation.setLongitude(station.getLongitude());
                    scaleStation.setStationid(station.getStationid());
                    scaleStation.setStationname(station.getStationname());
                    resultList.add(scaleStation);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }


    @Override
    public List<ActualData> qxElementQuery(ActualElemQuery elemQuery) {
        // TODO 气象要素统计
        List<tower_station> TowerdataList = new ArrayList<tower_station>();
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();

            List<String> countys = elemQuery.getCountys();
            // 获取查询字段
            List<String> columns = new ArrayList<String>();
            columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
            columns.add("stationname");
            columns.add("longitude");
            columns.add("latitude");
            columns.add("stationname");
            columns.add("county");
            StringBuilder strWhere = new StringBuilder();
            if (countys != null && countys.size() > 0) {
                strWhere.append("  county in (");
                String tempString = "";
                for (String county : countys) {
                    tempString += String.format("'%s',", county);
                }
                strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
            }
            selectRequest.setParam(strWhere.toString());
            selectParam.put("method", "tower_station");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            TowerdataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<tower_station>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }

        List<smallscale_station> stalist = new ArrayList<smallscale_station>();
        ArrayList<String> stationids = new ArrayList<String>();
        Map<String, String[]> map = new HashMap<String, String[]>();
        Map<String, MsgMediumSmallScale> map1 = new HashMap<String, MsgMediumSmallScale>();
        if (TowerdataList != null && TowerdataList.size() > 0) {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            List<String> columns = new ArrayList<String>();
            columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
            columns.add("stationname");
            columns.add("longitude");
            columns.add("latitude");
            selectRequest.setColumns(columns.toArray(new String[columns.size()]));
            try {
                selectParam.put("method", "smallscale_station");
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                stalist = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<smallscale_station>>() {
                });
//
            } catch (Exception e) {
                // TODO: handle exception
                System.err.println(e.getStackTrace());
            }
        }
//        }

        //判断选择最近乡镇站点
        for (int i = 0; i < TowerdataList.size(); i++) {
            Double min = 99999999.0;
            String lon = TowerdataList.get(i).getLongitude();
            String lat = TowerdataList.get(i).getLatitude();
            String stationid = "";
            String[] zuobiao = new String[4];
            for (int j = 0; j < stalist.size(); j++) {
                Double distance = (stalist.get(j).getLongitude() - Double.parseDouble(lon)) * (stalist.get(j).getLongitude() - Double.parseDouble(lon)) + (stalist.get(j).getLatitude() - Double.parseDouble(lat)) * (stalist.get(j).getLatitude() - Double.parseDouble(lat));
                if (distance < min) {
                    min = distance;
                    stationid = stalist.get(j).getStationid();
                }
            }
            zuobiao[0] = stationid;
            zuobiao[1] = TowerdataList.get(i).getStationname();
            zuobiao[2] = TowerdataList.get(i).getLongitude();
            zuobiao[3] = TowerdataList.get(i).getLatitude();
            stationids.add(stationid);
            map.put(TowerdataList.get(i).getStationid(), zuobiao);
        }

        List<ActualData> resultList = new ArrayList<ActualData>();
        List<MsgMediumSmallScale> dataList = new ArrayList<MsgMediumSmallScale>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String element = elemQuery.getElement();
        String type = elemQuery.getType();
        Date startDate = elemQuery.getStartDate();
        Date endDate = elemQuery.getEndDate();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (startDate != null) {
            whereCount++;
            strWhere.append(String.format("observTime >='%tF %tT'", startDate, startDate));
        }
        if (endDate != null) {
            strWhere.append(String.format(" and observTime <='%tF %tT'", endDate, endDate));
        }
        if (stationids != null && stationids.size() > 0) {
            strWhere.append(" and stationId in (");
            String tempString = "";
            for (String station : stationids) {
                tempString += String.format("'%s',", station);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        // 获取查询字段
        List<String> columns = new ArrayList<String>();
        columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
        columns.add("stationname");
        columns.add("longitude");
        columns.add("latitude");
        if (element != null && element.equals("rain")) {
            // 雨量和统计
            if (type != null && type.equals("sum")) {
                columns.add("sum(rain) as rain");
                selectRequest.setSort(new String[]{"rain desc"});
                strWhere.append(" and rain <> -65535");
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("sum(rain) as rain");
                    strWhere.append(" and rain <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("rain");
                    strWhere.append(" and rain <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }

        if (element != null && element.equals("temp")) {
            // 温度统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add("cast(" + type + "(cast(DryBulbTemp as numeric(18,1))) as FLOAT) as DryBulbTemp");
                strWhere.append(" and DryBulbTemp <> -65535");
                selectRequest.setSort(new String[]{"DryBulbTemp desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(DryBulbTemp) as DryBulbTemp");
                    strWhere.append(" and DryBulbTemp <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("DryBulbTemp");
                    strWhere.append(" and DryBulbTemp <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }

        if (element != null && element.equals("winds")) {
            // 风速统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add(type + "(InstantWindV) as InstantWindV");
                strWhere.append(" and InstantWindV <> -65535");
                selectRequest.setSort(new String[]{"InstantWindV desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(InstantWindV) as InstantWindV");
                    strWhere.append(" and InstantWindV <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("InstantWindV");
                    strWhere.append(" and InstantWindV <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("humid")) {
            // 湿度统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add("cast(" + type + "(RelHumidity) as integer) as RelHumidity");
                strWhere.append(" and RelHumidity <> -65535");
                selectRequest.setSort(new String[]{"RelHumidity desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(RelHumidity) as RelHumidity");
                    strWhere.append(" and RelHumidity <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("RelHumidity");
                    strWhere.append(" and RelHumidity <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("pressure")) {
            // 气压统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add(type + "(StationPress) as StationPress");
                strWhere.append(" and StationPress <> -65535");
                selectRequest.setSort(new String[]{"StationPress desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(StationPress) as StationPress");
                    strWhere.append(" and StationPress <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("StationPress");
                    strWhere.append(" and StationPress <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            if (DateTime.UserMainDataTable(elemQuery.getStartDate(), DbConfig.CACHEDAYS)) {
                selectParam.put("method", "msgmediumsmallscale");
            } else {
                selectParam.put("method", "msgmediumsmallscale");
            }
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<MsgMediumSmallScale>>() {
            });

            for (int i = 0; i < dataList.size(); i++) {
                map1.put(dataList.get(i).getStationid(), dataList.get(i));
            }

        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        // 赋值
        try {

            //赋值经纬度
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                String ttstaid = entry.getKey();
                String skstaid = entry.getValue()[0];
                ActualData actualData = new ActualData();
                actualData.setStationId(skstaid);
                actualData.setStationName(entry.getValue()[1]);
                actualData.setLon(Double.parseDouble(entry.getValue()[2]));
                actualData.setLat(Double.parseDouble(entry.getValue()[3]));
                DmMapPoint dt = iTransformService.LonLatConvertToLambert(Double.parseDouble(entry.getValue()[2]), Double.parseDouble(entry.getValue()[3]));
                actualData.setX(dt.x);
                actualData.setY(dt.y);


                switch (element) {
                    case "rain":
                        if (map1.get(skstaid) != null) {
                            actualData.setRain(Double.parseDouble(String.format("%.1f", map1.get(skstaid).getRain())));
                        }
                        break;
                    case "temp":
                        if (map1.get(skstaid) != null) {
                            actualData.setTemp(Double.parseDouble(String.format("%.1f", map1.get(skstaid).getDrybulbtemp())));
                        }
                        break;
                    case "humid":
                        if (map1.get(skstaid) != null) {
                            actualData.setHumid(Double.parseDouble(String.format("%d", map1.get(skstaid).getRelhumidity())));
                        }
                        break;
                    case "winds":
                        if (map1.get(skstaid) != null) {
                            actualData.setWinds(Double.parseDouble(String.format("%.1f", map1.get(skstaid).getInstantwindv())));
                        }
                        break;
                    case "pressure":
                        if (map1.get(skstaid) != null) {
                            actualData.setPressure(Double.parseDouble(String.format("%.1f", map1.get(skstaid).getStationpress())));
                        }
                        break;
                    default:
                        break;
                }

                if (map1.get(skstaid) != null) {
                    if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        actualData.setDateTime(sdf.parse(map1.get(skstaid).getDatechar()));
                    } else {
                        actualData.setDateTime(map1.get(skstaid).getObservtime());
                    }
                }
                resultList.add(actualData);
            }
        } catch (Exception e) {
            System.out.println(e);
            // TODO: handle exception
        }
        return resultList;
    }


    @Override
    public List<ElemContourSet> getElemContourSet(String elementType) {
        // TODO 获取图例
        List<contour_setting> dataList = new ArrayList<contour_setting>();
        List<ElemContourSet> resultList = new ArrayList<ElemContourSet>();
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            selectRequest.setParam(String.format("ElementType='%s'", elementType));
            selectRequest.setSort(new String[]{"elementvalue asc"});
            selectParam.put("method", "contour_setting");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<contour_setting>>() {
            });
            // 赋值
            if (dataList.size() > 0) {
                for (contour_setting setting : dataList) {
                    ElemContourSet elemSet = new ElemContourSet();
                    elemSet.setElementColor(setting.getElementcolor());
                    elemSet.setElementValue(setting.getElementvalue());
                    elemSet.setElemrntInstruction(setting.getElemrntinstruction());
                    resultList.add(elemSet);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }
    @Override
    public List<MediumSmallScale> getPoint(SmallScaleSearch smallscalesearch) {
        // TODO 获取整点雨量、温度、湿度、风速、气压
        List<tower_station> TowerdataList = new ArrayList<tower_station>();
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            // 获取查询字段
            List<String> columns = new ArrayList<String>();
            columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
            columns.add("stationname");
            columns.add("longitude");
            columns.add("latitude");
            columns.add("stationname");
            columns.add("county");
            selectParam.put("method", "tower_station");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            TowerdataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<tower_station>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }

        List<smallscale_station> stalist = new ArrayList<smallscale_station>();
        ArrayList<String> stationids = new ArrayList<String>();
        Map<String, String[]> map = new HashMap<String, String[]>();
        Map<String, msgmediumsmallscale> map1 = new HashMap<String, msgmediumsmallscale>();
        if (TowerdataList != null && TowerdataList.size() > 0) {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            List<String> columns = new ArrayList<String>();
            columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
            columns.add("stationname");
            columns.add("longitude");
            columns.add("latitude");
            selectRequest.setColumns(columns.toArray(new String[columns.size()]));
            try {
                selectParam.put("method", "smallscale_station");
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                stalist = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<smallscale_station>>() {
                });
            } catch (Exception e) {
                // TODO: handle exception
                System.err.println(e.getStackTrace());
            }
        }
        for (int i = 0; i < TowerdataList.size(); i++) {
            Double min = 99999999.0;
            String lon = TowerdataList.get(i).getLongitude();
            String lat = TowerdataList.get(i).getLatitude();
            String stationid = "";
            String[] zuobiao = new String[4];
            for (int j = 0; j < stalist.size(); j++) {
                Double distance = (stalist.get(j).getLongitude() - Double.parseDouble(lon)) * (stalist.get(j).getLongitude() - Double.parseDouble(lon)) + (stalist.get(j).getLatitude() - Double.parseDouble(lat)) * (stalist.get(j).getLatitude() - Double.parseDouble(lat));
                if (distance < min) {
                    min = distance;
                    stationid = stalist.get(j).getStationid();
                }
            }
            zuobiao[0] = stationid;
            zuobiao[1] = TowerdataList.get(i).getStationname();
            zuobiao[2] = TowerdataList.get(i).getLongitude();
            zuobiao[3] = TowerdataList.get(i).getLatitude();
            stationids.add(stationid);
            map.put(TowerdataList.get(i).getStationid(), zuobiao);
        }


        List<msgmediumsmallscale> listData = new ArrayList<msgmediumsmallscale>();
        List<MediumSmallScale> resultList = new ArrayList<MediumSmallScale>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        List<String> countys = smallscalesearch.getCountys();
        columns.add("observTime");
        columns.add("StationID");
        columns.add("Longitude");
        columns.add("Latitude");
        columns.add("rain");
        columns.add("CAST(replace(cast(DryBulbTemp AS VARCHAR),'-65535','99999') as float) as dryBulbTemp");
        columns.add("CAST(replace(cast(InstantWindV AS VARCHAR),'-65535','99999') as float) as instantWindV");
        columns.add("cast(replace(cast(RelHumidity AS VARCHAR),'-65535','99999') as integer) as relHumidity");
        columns.add("CAST(replace(cast(PressureSea AS VARCHAR),'-65535','99999') as float) as pressureSea");
        columns.add("CAST(replace(cast(visibility AS VARCHAR),'-65535','99999') as integer) as visibility");
        columns.add("stationname");
        columns.add("City");
        columns.add("County");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        selectRequest.setSort(new String[]{"StationID asc"});
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (smallscalesearch.getObservTime() != null) {
            strWhere.append(String.format(" and dateChar='%tF'", smallscalesearch.getObservTime()));
        }
        if (smallscalesearch.getStartDate() != null) {
            strWhere.append(String.format(" and observTime='%s'", smallscalesearch.getStartDate()));
        }
        if (!StringUtil.IsNullOrEmpty(smallscalesearch.getStationID())) {
            strWhere.append(String.format(" and StationID='%s'", smallscalesearch.getStationID()));
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        if (countys != null && countys.size() > 0) {
            strWhere.append(" and county in (");
            String tempString = "";
            for (String county : countys) {
                tempString += String.format("'%s',", county);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
            for (int i = 0; i < listData.size(); i++) {

                map1.put(listData.get(i).getStationid(), listData.get(i));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }


        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String ttstaid = entry.getKey();
            String skstaid = entry.getValue()[0];

            MediumSmallScale smallscale = new MediumSmallScale();

            smallscale.setStationID(skstaid);
            smallscale.setStationName(entry.getValue()[1]);
            smallscale.setLon(Double.parseDouble(entry.getValue()[2]));
            smallscale.setLat(Double.parseDouble(entry.getValue()[3]));
            smallscale.setLongitude(Double.parseDouble(entry.getValue()[2]));
            smallscale.setLatitude(Double.parseDouble(entry.getValue()[3]));
            DmMapPoint dt = iTransformService.LonLatConvertToLambert(Double.parseDouble(entry.getValue()[2]), Double.parseDouble(entry.getValue()[3]));
            smallscale.setX(dt.x);
            smallscale.setY(dt.y);

            if (map1.get(skstaid) != null) {
                smallscale.setObservTime(map1.get(skstaid).getObservtime());
                smallscale.setRain(map1.get(skstaid).getRain());
                smallscale.setDryBulbTemp(map1.get(skstaid).getDrybulbtemp());
                smallscale.setInstantWindV(map1.get(skstaid).getInstantwindv());
                smallscale.setRelHumidity(map1.get(skstaid).getRelhumidity());
                smallscale.setPressureSea(map1.get(skstaid).getPressuresea());
                smallscale.setCity(map1.get(skstaid).getCity());
                smallscale.setCounty(map1.get(skstaid).getCounty());
                smallscale.setVisibility(map1.get(skstaid).getVisibility());
                resultList.add(smallscale);
            }
        }
            return resultList;
        }


    @Override
    public List<base_product> getTouristProduct(int id, String productType, String startDate, String endDate) {
        // TODO Auto-generated method stub
        List<base_product> resultList = new ArrayList<base_product>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        if (id > 0) {
            whereCount++;
            strWhere.append(String.format("id=%d", id));
        }
        if (!StringUtil.IsNullOrEmpty(productType)) {
            strWhere.append(String.format("and productType='%s'", productType));
        }
        if (!StringUtil.IsNullOrEmpty(startDate)) {
            strWhere.append(String.format(" and maketime>='%s'", startDate));
        }
        if (!StringUtil.IsNullOrEmpty(endDate)) {
            strWhere.append(String.format(" and maketime<='%s'", endDate));
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"maketime desc"});
        try {
            selectParam.put("method", "base_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }


    @Override
    public List<DZWarning> getDzpart(String bindid) {
        // TODO 地灾对应id的预警区
        List<dz_warning> listData = new ArrayList<dz_warning>();
        List<DZWarning> resultList = new ArrayList<DZWarning>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(bindid)) {
            strWhere.append(String.format(" and docid='%s'", bindid));
        }
        if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"datechar desc"});
        try {
            selectParam.put("method", "dz_warning");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<dz_warning>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (listData != null && listData.size() > 0) {
            for (dz_warning dzWarn : listData) {
                DZWarning dzWarning = new DZWarning();
                dzWarning.setDocid(dzWarn.getDocid());
                dzWarning.setDateChar(dzWarn.getDatechar());
                dzWarning.setPos(dzWarn.getPos());
                dzWarning.setGradeArea2(dzWarn.getGradearea2());
                dzWarning.setGradeArea3(dzWarn.getGradearea3());
                dzWarning.setGradeArea4(dzWarn.getGradearea4());
                dzWarning.setGradeArea5(dzWarn.getGradearea5());
                dzWarning.setDocpath(dzWarn.getDocpath());
                resultList.add(dzWarning);
            }
        }
        return resultList;
    }



    @Override
    public List<sl_warning> getshpart(String bindid) {
        // TODO 山洪对应id的预警区
        List<sl_warning> listData = new ArrayList<sl_warning>();
        List<sl_warning> resultList = new ArrayList<sl_warning>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(bindid)) {
            strWhere.append(String.format(" and docid='%s'", bindid));
        }
        if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"datechar desc"});
        try {
            selectParam.put("method", "sl_warning");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<sl_warning>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (listData != null && listData.size() > 0) {
            for (sl_warning dzWarn : listData) {
                sl_warning dzWarning = new sl_warning();
                dzWarning.setDocid(dzWarn.getDocid());
                dzWarning.setDatechar(dzWarn.getDatechar());
                dzWarning.setPos(dzWarn.getPos());
                dzWarning.setGradearea2(dzWarn.getGradearea2());
                dzWarning.setGradearea3(dzWarn.getGradearea3());
                dzWarning.setGradearea4(dzWarn.getGradearea4());
                dzWarning.setGradearea5(dzWarn.getGradearea5());
                dzWarning.setDocpath(dzWarn.getDocpath());
                resultList.add(dzWarning);
            }
        }
        return resultList;
    }




    @Override
    public Date getDZNewDate() {

        base_product newDate = new base_product();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(maketime, 'yyyy-MM-dd HH24:MI:SS') as maketime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam("productType='铁塔地质灾害预报'");
        selectRequest.setSort(new String[]{"maketime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "base_product");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
            }).get(0);
        } catch (Exception e) {
            // TODO: handle exception
            newDate.setMaketime(DateTime.now().toDate());
        }
        return newDate.getMaketime();
    }



    @Override
    public Date getshNewDate() {

        base_product newDate = new base_product();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(maketime, 'yyyy-MM-dd HH24:MI:SS') as maketime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam("productType='铁塔山洪灾害预报'");
        selectRequest.setSort(new String[]{"maketime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "base_product");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
            }).get(0);
        } catch (Exception e) {
            // TODO: handle exception
            newDate.setMaketime(DateTime.now().toDate());
        }
        return newDate.getMaketime();
    }



    @Override
    public Date getqsNewDate() {
        base_product newDate = new base_product();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(maketime, 'yyyy-MM-dd HH24:MI:SS') as maketime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam("productType='潜势预报'");
        selectRequest.setSort(new String[]{"maketime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "base_product");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
            }).get(0);
        } catch (Exception e) {
            // TODO: handle exception
            newDate.setMaketime(DateTime.now().toDate());
        }
        return newDate.getMaketime();
    }



    @Override
    public Date getnlNewDate() {
        base_product newDate = new base_product();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(maketime, 'yyyy-MM-dd HH24:MI:SS') as maketime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam("productType='铁塔城市内涝预报'");
        selectRequest.setSort(new String[]{"maketime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "base_product");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
            }).get(0);
        } catch (Exception e) {
            // TODO: handle exception
            newDate.setMaketime(DateTime.now().toDate());
        }
        return newDate.getMaketime();
    }




    @Override
    public List<waterlogging_fcst> getnlpart(String bindid) {
        // TODO 内涝对应id的预警区
        List<waterlogging_fcst> listData = new ArrayList<waterlogging_fcst>();
        List<waterlogging_fcst> resultList = new ArrayList<waterlogging_fcst>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(bindid)) {
            strWhere.append(String.format(" and id='%s'", bindid));
        }
        if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"maketime desc"});
        try {
            selectParam.put("method", "waterlogging_fcst");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<waterlogging_fcst>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (listData != null && listData.size() > 0) {
            for (waterlogging_fcst dzWarn : listData) {
                waterlogging_fcst dzWarning = new waterlogging_fcst();
                dzWarning.setDocid(dzWarn.getDocid());
                dzWarning.setMaketime(dzWarn.getMaketime());
                dzWarning.setPos(dzWarn.getWarnpos());
                dzWarning.setDocpath(dzWarn.getDocpath());
                resultList.add(dzWarning);
            }
        }
        return resultList;
    }




    @Override
    public List<tour_stations> getTourStation() {
        // TODO 景点
        List<tour_stations> resultList = new ArrayList<tour_stations>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        try {
            selectParam.put("method", "tour_stations");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<tour_stations>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }

    @Override
    public List<potential_points> getDisPoint(List<String> dpoint) {
        // TODO 获取关联灾害点的具体信息
        List<potential_points> listData = new ArrayList<potential_points>();
        List<DPoint> resultList = new ArrayList<DPoint>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        if (dpoint != null && dpoint.size() > 0) {
            strWhere.append(" and pp_id in (");
            String tempString = "";
            for (String station : dpoint) {
                tempString += String.format("'%s',", station);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "potential_points");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<potential_points>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return listData;
    }

    }

